package com.yanqu.road.server.timer.peakstronghold;

import com.alibaba.fastjson.JSON;
import com.yanqu.road.dao.impl.curio.UserCurioSkillDataDaoImpl;
import com.yanqu.road.entity.activity.peakstronghold.UserPeakStrongholdWarData;
import com.yanqu.road.entity.activity.peakstronghold.config.PeakStrongHoldConfig;
import com.yanqu.road.entity.enums.eSkillType;
import com.yanqu.road.entity.player.UserBaseInfo;
import com.yanqu.road.entity.player.UserHistoryAttribute;
import com.yanqu.road.entity.player.UserPatrons;
import com.yanqu.road.entity.union.UnionBaseInfo;
import com.yanqu.road.entity.union.UnionMember;
import com.yanqu.road.logic.bussiness.player.UserHistoryAttributeBussiness;
import com.yanqu.road.logic.bussiness.player.UserPatronsBussiness;
import com.yanqu.road.logic.bussiness.player.activity.PeakStrongholdBusiness;
import com.yanqu.road.logic.pb.PlayerBasePb;
import com.yanqu.road.logic.pb.UnionBasePb;
import com.yanqu.road.message.YanQuMessage;
import com.yanqu.road.pb.activity.PeakStrongholdWarProto;
import com.yanqu.road.server.GameServer;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.gameplayer.module.activity.peakstronghold.PeakStrongholdModule;
import com.yanqu.road.server.gameplayer.module.patrons.PatronsModule;
import com.yanqu.road.server.gameplayer.module.player.PlayerModule;
import com.yanqu.road.server.manger.activity.curio.CurioMgr;
import com.yanqu.road.server.manger.activity.peakstronghold.PeakStrongholdActivityMgr;
import com.yanqu.road.server.manger.activity.strongholdwar.StrongholdWarMgr;
import com.yanqu.road.server.manger.config.VehicleMgr;
import com.yanqu.road.server.manger.manor.FishPondMgr;
import com.yanqu.road.server.manger.player.GamePlayerMgr;
import com.yanqu.road.server.manger.player.UserMgr;
import com.yanqu.road.server.manger.union.CrossUnionMgr;
import com.yanqu.road.server.protocol.GameErrorCode;
import com.yanqu.road.server.protocol.Protocol;
import com.yanqu.road.sync.message.SyncResponse;
import com.yanqu.road.utils.YanQuMessageUtils;
import com.yanqu.road.utils.config.Config;
import com.yanqu.road.utils.executor.GeneralTask;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;

public class PeakStrongholdTakeDataTask extends GeneralTask {

    @Override
    public void doRun() {
        // 3秒一次
        long param = 3;
        long secondIndex = System.currentTimeMillis() / 1000 % param;
        long canSendIndex = GameServer.getInstance().getServerId() % param;
        if (secondIndex == canSendIndex) {
            PeakStrongHoldConfig config = PeakStrongholdActivityMgr.getConfig();
            if (null == config || null == config.getActivityInfo()) {
                return;
            }
            int activityId = config.getActivityInfo().getActivityId();

            //报名阶段取门客赚钱数据
//            List<Long> takeUserIds = PeakStrongholdActivityMgr.popWaitTakeAbilityMembers(config.getTakeUserCount());
//            if (!takeUserIds.isEmpty()) {
//
//                List<PeakStrongholdWarProto.UserBaseMsg> userBaseMsgList = new ArrayList<>();
//                Map<String, List<PeakStrongholdWarProto.PeakHoldMemberAbilityTemp>> abilityMsgMap = new HashMap<>();
//
//                for (Long userId : takeUserIds) {
//                    UnionMember member = CrossUnionMgr.getUnionMember(userId);
//                    if (null == member) {
//                        //取数据时已经不在商会
//                        continue;
//                    }
//                    String unionId = member.getUnionUid();
//
//                    GamePlayer player = GamePlayerMgr.getOnlinePlayer(userId);
//
//                    BigInteger ability = BigInteger.ZERO;
//                    if (null != player) {
//                        UserHistoryAttribute userHistoryAttribute = player.getModule(PlayerModule.class).getUserHistoryAttribute();
//                        ability = userHistoryAttribute.getAbility();
//                    } else {
//                        UserHistoryAttribute userHistoryAttribute = UserHistoryAttributeBussiness.getUserHistoryAttribute(userId);
//                        if(null == userHistoryAttribute) {
//                            continue;
//                        }
//                        ability = userHistoryAttribute.getAbility();
//                    }
//                    PeakStrongholdWarProto.PeakHoldMemberAbilityTemp.Builder abilityMsg = PeakStrongholdWarProto.PeakHoldMemberAbilityTemp.newBuilder();
//                    abilityMsg.setUserId(userId);
//                    abilityMsg.setTotalAbility(ability.toString());
//
//                    List<PeakStrongholdWarProto.PeakHoldMemberAbilityTemp> abilityMap = abilityMsgMap.get(unionId);
//                    if (null == abilityMap) {
//                        abilityMap = new ArrayList<>();
//                        abilityMsgMap.put(unionId, abilityMap);
//                    }
//                    abilityMap.add(abilityMsg.build());
//
//                    UserBaseInfo userBaseInfo = UserMgr.getUserBaseInfo(userId, GameServer.getInstance().getServerId());
//                    PeakStrongholdWarProto.UserBaseMsg.Builder userBaseMsg = PeakStrongholdWarProto.UserBaseMsg.newBuilder();
//                    userBaseMsg.setUserId(userId);
//                    userBaseMsg.setUserBaseMsg(PlayerBasePb.parsePlayerBaseTempMsg(userBaseInfo));
//                    userBaseMsgList.add(userBaseMsg.build());
//                }
//
//                PeakStrongholdWarProto.CrossPeakHoldUnionMemberAbilityResp.Builder syncMsg = PeakStrongholdWarProto.CrossPeakHoldUnionMemberAbilityResp.newBuilder();
//                syncMsg.setActivityId(activityId);
//
//                for (Map.Entry<String, List<PeakStrongholdWarProto.PeakHoldMemberAbilityTemp>> abilityMsg : abilityMsgMap.entrySet()) {
//                    String unionId = abilityMsg.getKey();
//                    PeakStrongholdWarProto.PeakHoldUnionAbilityTemp.Builder unionAbilityMsg = PeakStrongholdWarProto.PeakHoldUnionAbilityTemp.newBuilder();
//                    UnionBaseInfo unionBaseInfoInfo = CrossUnionMgr.parseUnionBaseInfo(unionId);
//                    List<Long> memberIds = CrossUnionMgr.getUnionMemberIdList(unionId);
//                    unionAbilityMsg.setUnionId(unionId);
//                    unionAbilityMsg.addAllMemberIds(memberIds);
//                    unionAbilityMsg.setUnionBaseInfo(UnionBasePb.parseUnionBaseTempMsg(unionBaseInfoInfo));
//                    unionAbilityMsg.addAllMemberInfo(abilityMsg.getValue());
//                    syncMsg.addUnionAbility(unionAbilityMsg);
//                }
//
//                YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.C_PEAK_STRONGHOLD_NOTIFY_UPDATE_MEMBER_ABILITY_RESP, syncMsg);
//                GamePlayerMgr.sendPacket(0, pbMsg);
//
//                if (!userBaseMsgList.isEmpty()) {
//                    PeakStrongholdWarProto.CrossPeakHoldUpdateUserBaseMsg.Builder updateUserBaseMsg = PeakStrongholdWarProto.CrossPeakHoldUpdateUserBaseMsg.newBuilder();
//                    updateUserBaseMsg.setActivityId(activityId);
//                    updateUserBaseMsg.addAllUserBaseMsgList(userBaseMsgList);
//                    GamePlayerMgr.sendPacket(0, YanQuMessageUtils.buildMessage(Protocol.C_PEAK_STRONGHOLD_UPDATE_USER_BASE_INFO, updateUserBaseMsg));
//                }
//            }

            //准备阶段取防守门客
            Map<Integer, List<Long>> takeUserIdsMap = PeakStrongholdActivityMgr.popWaitTakeDefendPatronsMembers(config.getTakeUserCount());
            for (Map.Entry<Integer, List<Long>> entry : takeUserIdsMap.entrySet()) {
                Integer unionGroup = entry.getKey();
                List<Long> takeUserIds = entry.getValue();
                if (!takeUserIds.isEmpty()) {
                    List<PeakStrongholdWarProto.UserBaseMsg> userBaseMsgList = new ArrayList<>();
                    PeakStrongholdWarProto.CrossPeakHoldDefendPatronUpdateRespMsg.Builder syncMsg = PeakStrongholdWarProto.CrossPeakHoldDefendPatronUpdateRespMsg.newBuilder();
                    syncMsg.setActivityId(activityId);
                    syncMsg.setUnionGroup(unionGroup);

                    for (Long userId : takeUserIds) {
                        UnionMember member = CrossUnionMgr.getUnionMember(userId);
                        if (null == member) {
                            //取数据时已经不在商会
                            continue;
                        }

                        PeakStrongholdWarProto.CrossPeakHoldDefendUserInfoTemp.Builder userDefendMsg = PeakStrongholdWarProto.CrossPeakHoldDefendUserInfoTemp.newBuilder();
                        userDefendMsg.setUserId(userId);
                        userDefendMsg.setUnionId(member.getUnionUid());
                        long otherAddition = 0;
                        UserPeakStrongholdWarData userHoldData = null;
                        List<UserPatrons> topPatrons = new ArrayList<>();
                        Map<Integer, UserPatrons> patronsMap = new HashMap<>();
                        int donateExp = 0;
                        BigInteger silverAmount = BigInteger.ZERO;
                        GamePlayer player = GamePlayerMgr.getOnlinePlayer(userId);
                        if (null != player) {
                            patronsMap = player.getModule(PatronsModule.class).getUserPatronsMap();
                            PeakStrongholdModule moudle = player.getModule(PeakStrongholdModule.class);
                            userHoldData = moudle.getPeakStrongholdWarData(activityId);
                            topPatrons = moudle.getTopEarnSpeedPatrons();

                            silverAmount = userHoldData.getSilverAmount();
                            donateExp = userHoldData.getDonateExp();

                            otherAddition = StrongholdWarMgr.getOtherAddition(player);

                        } else {
                            Map<Integer, UserPeakStrongholdWarData> userHoldDataMap = PeakStrongholdBusiness.getStrongholdWarUserData(userId);
                            userHoldData = userHoldDataMap.get(activityId);
                            if (null != userHoldData) {
                            /*if (userHoldData.getSilverRound() == config.getRound()) {
                                silverAmount = userHoldData.getSilverAmount();
                            }*/
                                //不用重置了，直接上
                                silverAmount = userHoldData.getSilverAmount();
                                donateExp = userHoldData.getDonateExp();
                            }

                            patronsMap = UserPatronsBussiness.getUserPatronsAndSkillMap(userId);
                            if (patronsMap != null && patronsMap.size() > 0) {
                                topPatrons = PeakStrongholdActivityMgr.getUserPatronsByEarnSpeedRank(config.getTopDefendPatronsNum(), new ArrayList<>(patronsMap.values()));
                            }

                            otherAddition = new UserCurioSkillDataDaoImpl().getUserCurioSkillAddition(userId, CurioMgr.getSkillIdList(eSkillType.StrongholdWarPatronsSkill.getValue()));
                        }

                        userDefendMsg.setSilverAmount(silverAmount.toString());
                        userDefendMsg.setDonateExp(donateExp);

                        for (UserPatrons userPatrons : topPatrons) {
                            PeakStrongholdWarProto.CrossPeakHoldDefendPatronInfoTemp.Builder defendPatronMsg = PeakStrongholdWarProto.CrossPeakHoldDefendPatronInfoTemp.newBuilder();
                            defendPatronMsg.setPatronsId(userPatrons.getPatronsId());
                            defendPatronMsg.setSkinId(userPatrons.getSkinId());
                            defendPatronMsg.setLevel(userPatrons.getLevel());
                            defendPatronMsg.setStageLv(userPatrons.getStageLv());
                            BigInteger totalAbility = StrongholdWarMgr.calcStrongholdPatronsTotalAbility(userPatrons, patronsMap, otherAddition);
                            defendPatronMsg.setAbility(totalAbility.toString());

                            userDefendMsg.addPatronInfos(defendPatronMsg);

                            // 绑定珍兽和鱼相关接口
                       /* VehicleMgr.bindVehicleToPatrons(activityId, userId, userPatrons.getPatronsId());
                        FishPondMgr.bindFishToPatrons(activityId, userId, userPatrons.getPatronsId());*/
                        }
                        syncMsg.addUserDefendInfos(userDefendMsg);

                        UserBaseInfo userBaseInfo = UserMgr.getUserBaseInfo(userId, GameServer.getInstance().getServerId());
                        PeakStrongholdWarProto.UserBaseMsg.Builder userBaseMsg = PeakStrongholdWarProto.UserBaseMsg.newBuilder();
                        userBaseMsg.setUserId(userId);
                        userBaseMsg.setUserBaseMsg(PlayerBasePb.parsePlayerBaseTempMsg(userBaseInfo));
                        userBaseMsgList.add(userBaseMsg.build());
                    }

                    GamePlayerMgr.sendUnionActivityGroupPacket(Protocol.C_PEAK_STRONGHOLD_NOTIFY_UPDATE_MEMBER_DEFEND_RESP, syncMsg, 0, activityId, unionGroup);

                    if (Config.isDebug()) {
                        PeakStrongholdActivityMgr.getLogger().info("巅峰据点战上传玩家{}的防守数据", JSON.toJSONString(takeUserIds));
                    }

                    if (!userBaseMsgList.isEmpty()) {
                        PeakStrongholdWarProto.CrossPeakHoldUpdateUserBaseMsg.Builder updateUserBaseMsg = PeakStrongholdWarProto.CrossPeakHoldUpdateUserBaseMsg.newBuilder();
                        updateUserBaseMsg.setActivityId(activityId);
                        updateUserBaseMsg.addAllUserBaseMsgList(userBaseMsgList);
                        GamePlayerMgr.sendUnionActivityGroupPacket(Protocol.C_PEAK_STRONGHOLD_UPDATE_USER_BASE_INFO, updateUserBaseMsg, 0, activityId, unionGroup);
                    }

                }
            }

            //淘汰赛名单检查
            PeakStrongholdActivityMgr.checkEliminateUnionList();
        }
    }
}
